"use client";

import { useEffect, useRef, useMemo } from 'react';
import { Carousel } from 'antd';
import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.css';

interface ProductScreenshotsProps {
  screenshots: string[];
  productTitle: string;
}

export default function ProductScreenshots({ screenshots, productTitle }: ProductScreenshotsProps) {
  const viewerRef = useRef<Viewer | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  // 使用useMemo来稳定screenshots的引用
  const stableScreenshots = useMemo(() => screenshots, [screenshots]);

  useEffect(() => {
    // 如果没有截图，不初始化viewer
    if (!stableScreenshots || stableScreenshots.length === 0) {
      return;
    }

    if (containerRef.current && stableScreenshots.length > 0) {
      try {
        // 如果已经存在viewer实例，先销毁
        if (viewerRef.current) {
          viewerRef.current.destroy();
        }
        
        // 初始化viewer
        viewerRef.current = new Viewer(containerRef.current, {
          inline: false,
          button: true,
          navbar: true,
          title: true,
          toolbar: true,
          tooltip: true,
          movable: true,
          zoomable: true,
          rotatable: true,
          scalable: true,
          transition: true,
          fullscreen: true,
          keyboard: true,
          url: 'data-source',
        });
      } catch (error) {
        console.error('Failed to initialize viewer:', error);
      }
    }

    return () => {
      if (viewerRef.current) {
        try {
          viewerRef.current.destroy();
        } catch (error) {
          console.error('Failed to destroy viewer:', error);
        } finally {
          viewerRef.current = null;
        }
      }
    };
  }, [stableScreenshots]);

  // 如果没有截图，不渲染组件
  if (!screenshots || screenshots.length === 0) {
    return null;
  }

  return (
    <div className='bg-white rounded-xl shadow-md p-6 md:p-8'>
      <h2 className='text-2xl font-bold text-slate-800'>产品截图</h2>
      
      {/* Viewer容器 - 隐藏的图片列表 */}
      <div ref={containerRef} style={{ display: 'none' }}>
        {screenshots.map((url: string, idx: number) => (
          <img
            key={idx}
            src={url}
            alt={`${productTitle} 截图 ${idx + 1}`}
            data-source={url}
            data-title={`${productTitle} 截图 ${idx + 1}`}
          />
        ))}
      </div>

      {/* 显示的轮播图 */}
      <Carousel
        arrows
        draggable
        swipeToSlide
        dots
        infinite
        slidesToShow={2}
        responsive={[
          { breakpoint: 1280, settings: { slidesToShow: 2 } },
          { breakpoint: 1024, settings: { slidesToShow: 2 } },
          { breakpoint: 768, settings: { slidesToShow: 1 } },
        ]}
        className='custom-screenshots-carousel'
      >
        {screenshots.map((url: string, idx: number) => (
          <div key={idx}>
            <div style={{ 
              padding: 10, 
              position: "relative",
              height: "300px",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              minHeight: "250px"
            }}>
              <div style={{ position: "relative", width: "100%", height: "100%" }}>
                <img
                  src={url}
                  alt={`${productTitle} 截图 ${idx + 1}`}
                  style={{ 
                    width: "100%", 
                    height: "100%", 
                    objectFit: "contain", 
                    borderRadius: "8px",
                    cursor: "pointer"
                  }}
                  onClick={() => {
                    try {
                      if (viewerRef.current) {
                        viewerRef.current.view(idx);
                      }
                    } catch (error) {
                      console.error('Failed to view image:', error);
                    }
                  }}
                />
                <div
                  style={{
                    position: "absolute",
                    right: 10,
                    bottom: 20,
                    padding: "4px 8px",
                    borderRadius: 9999,
                    background: "rgba(0,0,0,0.6)",
                    color: "#fff",
                    fontSize: 12,
                    lineHeight: 1,
                    letterSpacing: 0.3,
                    boxShadow: "0 2px 6px rgba(0,0,0,0.15)",
                  }}
                >
                  {idx + 1}/{screenshots.length}
                </div>
              </div>
            </div>
          </div>
        ))}
      </Carousel>
    </div>
  );
}
